package com.zklh.leetcode.tree.middle;

import com.zklh.leetcode.tree.model.NestedInteger;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * 嵌套迭代器
 *
 * @author 坐看落花
 * @version 1.0
 * @date 2021/5/30 14:54
 */
public class NestedIterator implements Iterator<Integer> {

    private Iterator<Integer> iterator;

    @Override
    public boolean hasNext() {
        return iterator.hasNext();
    }

    @Override
    public Integer next() {
        return iterator.next();
    }

    /**
     * 在构造方法中拍平集合
     * @param list
     */
    public NestedIterator(List<NestedInteger> list) {
        List<Integer> table = new LinkedList<>();
        traverse(list, table);
        iterator = table.iterator();
    }


    /**
     * 遍历list, 用于铺平集合
     * @param list
     * @param table
     */
    private void traverse(List<NestedInteger> list, List<Integer> table) {
        if (list == null || list.isEmpty()) {
            return;
        }
        for (NestedInteger nestedInteger : list) {
            if (nestedInteger.isInteger()) {
                table.add(nestedInteger.getInteger());
            } else {
                traverse(nestedInteger.getList(), table);
            }
        }
    }


}
